package com.example.myactspringboot.util;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;

/**
 * 公共的合并单元格类，支持自定义合并策略
 */
public class CommonMergeStrategy extends AbstractMergeStrategy {
    // 合并策略list
    private List<CellRangeAddress> cellRangeAddresssList;

    // 通过有参数构造方法，设置合并策略
    public CommonMergeStrategy(List<CellRangeAddress> list) {
        this.cellRangeAddresssList = list;
    }

    /**
     * 重写合并策略方法
     * @param sheet sheet
     * @param cell cell
     * @param head head
     * @param relativeRowIndex relativeRowIndex
     */
    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, int relativeRowIndex) {
        // 将自定义合并策略假如excel
        if (CollectionUtils.isNotEmpty(cellRangeAddresssList)) {
//            if (cell.getRowIndex() == 1 && cell.getColumnIndex() == 0) {
            for (CellRangeAddress item : cellRangeAddresssList) {
                sheet.addMergedRegionUnsafe(item);
            }
            cellRangeAddresssList=null;
//            }
        }
    }
}
